package util

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"mp3/entity"
	"os"
	"path/filepath"
	"strings"
)

func ReadConfigs(path string, entities []entity.DownloadEntity) []entity.DownloadEntity {
	files, _ := ioutil.ReadDir(path)

	for _, f := range files {
		if f.IsDir() {
			path = CombinationFielPath(path, f.Name())
			entities = ReadConfigs(path, entities)
		} else if strings.HasSuffix(f.Name(), "tingzh_config.json") {
			configPath := CombinationFielPath(path, f.Name())
			entity := ReadConfig(configPath)

			entities = append(entities, entity)
		}
	}
	return entities
}

func CombinationFielPath(path string, name string) string {
	var configPath string
	if strings.Index(path, "/") > 0 {
		configPath = path + "/" + name
		//configPath = strings.ReplaceAll(configPath, "\\\\", "/")
		//configPath = strings.ReplaceAll(configPath, "\\", "/")
	} else {
		configPath = path + "/" + name
		//configPath = strings.ReplaceAll(configPath, "/", "\\")
	}
	return configPath
}

/*
判断文件是否存在
@parent fileName 文件名称
@parent configEntity  配置文件
*/
func SwitchFileExsts1(fileName string, configEntity entity.DownloadEntity) bool {
	files, _ := ioutil.ReadDir(configEntity.FileDirPath)
	for _, f := range files {
		if strings.Index(f.Name(), fileName) > -1 {
			return false
		}
	}

	return true
}

// 读取json配置文件
func ReadConfig(path string) entity.DownloadEntity {
	log.Println("[", path, "]")
	f, _ := os.Open(path)
	defer f.Close()
	buf := make([]byte, 1024)
	var chunk []byte
	//builder := strings.Builder{}

	for {
		//从file读取到buf中
		n, _ := f.Read(buf)
		//说明读取结束
		if n == 0 {
			break
		}
		//读取到最终的缓冲区中
		chunk = append(chunk, buf[:n]...)
	}
	var entity entity.DownloadEntity

	json.Unmarshal(chunk, &entity)
	entity.FileName = f.Name()
	if IsEmpty(entity.NextChildHref) {
		entity.NextChildHref = "href"
	}

	if IsEmpty(entity.AudioType) {
		entity.AudioType = ".mp3"
	}

	if IsEmpty(entity.PlayListChildTag) {
		entity.PlayListChildTag = "a"
	}

	if IsEmpty(entity.FFmpeg) {
		entity.FFmpeg = "ffmpeg"
	}
	entity.FFmpeg = strings.ToLower(entity.FFmpeg)
	if IsEmpty(entity.FFprobe) {
		entity.FFprobe = "ffprobe"
	}
	entity.FFprobe = strings.ToLower(entity.FFprobe)

	if IsEmpty(entity.NextChildHref) {
		entity.NextChildHref = "href"
	}

	if existsDir(entity.FileDirPath) {
		log.Println("--->", entity.FileDirPath)

		os.MkdirAll(entity.FileDirPath, os.ModePerm)
	}

	entity.ConfigPath = path

	return entity
}

func WriteConfigOfStartIndex(config entity.DownloadEntity, childIndex int) {

	f, error := os.Create(config.ConfigPath)
	defer f.Close()

	if nil != error {
		log.Println("文件读取失败", error.Error())
		return
	}

	encoder := json.NewEncoder(f)

	config.ConfigPath = ""
	config.FileName = ""

	error = encoder.Encode(config)
	if error != nil {
		log.Println("编码错误", error.Error())
	}
}

/*判断文件夹是否存在*/
func existsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return os.IsNotExist(err)
	}
	return !s.IsDir()
}

func RemoveFile(path string) {
	programPath, _ := filepath.Abs(path)
	os.Remove(programPath)
}
